﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using Contrib.Sms.Models;
using Orchard;
using Orchard.ContentManagement;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Messaging.Models;
using Orchard.Messaging.Services;
using Twilio;
using System.Linq;

namespace Contrib.Sms.Services
{
    public class SmsMessagingChannel : IMessagingChannel
    {
        private readonly IOrchardServices orchardServices;
        public const string SmsService = "sms";

        public ILogger Logger { get; set; }
        public Localizer T { get; set; }

        public SmsMessagingChannel(IOrchardServices orchardServices)
        {
            this.orchardServices = orchardServices;
            Logger = NullLogger.Instance;
        }

        public void SendMessage(MessageContext context)
        {
            if (!context.Service.Equals(SmsService, StringComparison.InvariantCultureIgnoreCase))
                return;

            var twilioSettings = orchardServices.WorkContext.CurrentSite.As<TwilioSettingsPart>();

            // can't process sms's if the twilio settings have not yet been set
            if (twilioSettings == null || !twilioSettings.IsValid())
            {
                return;
            }

            if (context.Addresses.Count() == 0)
            {
                Logger.Error("Recipient is missing a mobile number");
                return;
            }

            TwilioRestClient smsClient = new TwilioRestClient(twilioSettings.AccountSID, twilioSettings.AuthToken);

            foreach (var number in context.Addresses)
	        {
		        try
                {
                    var msg = smsClient.SendSmsMessage(twilioSettings.FromNumber, number, context.MailMessage.Body);
                    Logger.Debug("Message sent to {0}: {1}", number, context.Type);
                }
                catch(Exception e)
                {
                    Logger.Error(e, "An unexpected error while sending a message to {0}: {1}", number, context.Type);
                }
	        }
        }

        public IEnumerable<string> GetAvailableServices()
        {
            return new[] { SmsService };
        }
    }
}